/****************************************************************************

Tallulah - Projeto LES

****************************************************************************/

#include <QtGui>
#include <QTableWidgetItem>

#include "mdichild.h"

MdiChild::MdiChild()
{
	qt = 0;
	layout = new QVBoxLayout;
	formLay = new QVBoxLayout;
	formLay->setDirection(QBoxLayout::Down);

	botoes = new QWidget;
	botLay = new QHBoxLayout;
	add = new QPushButton;
	del = new QPushButton;
	add->setText(tr("Adicionar"));
	del->setText(tr("Remover"));
	botLay->addWidget(add);
	botLay->addWidget(del);
	botoes->setLayout(botLay);

	scrollArea = new QScrollArea(this);
	scrollArea->setObjectName(QString::fromUtf8("scrollArea"));
	scrollArea->setEnabled(true);
	scrollArea->setGeometry(QRect(0, 0, 781, 331));
	scrollArea->setMinimumSize(QSize(781, 331));
	scrollArea->setLineWidth(0);
	scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	scrollArea->setWidgetResizable(true);
	scrollArea->setAlignment(Qt::AlignLeft|Qt::AlignTop);
	scrollAreaWidgetContents = new QWidget();
	scrollAreaWidgetContents->setObjectName(QString::fromUtf8("scrollAreaWidgetContents"));
//	scrollAreaWidgetContents->setGeometry(QRect(0, 0, 761, 80));
	scrollAreaWidgetContents->setLayout(formLay);

	scrollArea->setWidget(scrollAreaWidgetContents);

	layout->addWidget(scrollArea);
	layout->addWidget(botoes);
	setLayout(layout);

	connect(add, SIGNAL(pressed()), this, SLOT(adicionar()));
	connect(del, SIGNAL(pressed()), this, SLOT(remover()));
}

void MdiChild::novaPergunta(int qt){

// -----------------------------------------------
/*	questao[qt] = new QGroupBox(scrollAreaWidgetContents);
	questao[qt]->setObjectName(QString::fromUtf8("questao"));
	questao[qt]->setGeometry(QRect(0, 0, 761, 80));
	questao[qt]->setMinimumSize(QSize(761, 80));
	questao[qt]->setMaximumSize(QSize(761, 80));
	questao[qt]->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);

	lineVariavel[qt] = new QLineEdit(questao[qt]);
	lineVariavel[qt]->setObjectName(QString::fromUtf8("lineVariavel"));
	lineVariavel[qt]->setGeometry(QRect(340, 40, 101, 20));

	linePergunta[qt] = new QLineEdit(questao[qt]);
	linePergunta[qt]->setObjectName(QString::fromUtf8("linePergunta"));
	linePergunta[qt]->setGeometry(QRect(10, 40, 321, 20));

	groupDominio[qt] = new QGroupBox(questao[qt]);
	groupDominio[qt]->setObjectName(QString::fromUtf8("groupDominio"));
	groupDominio[qt]->setGeometry(QRect(530, 20, 221, 51));

	comboDominio1[qt] = new QComboBox(groupDominio[qt]);
	comboDominio1[qt]->setObjectName(QString::fromUtf8("comboDominio1"));
	comboDominio1[qt]->setGeometry(QRect(10, 20, 41, 22));

	spinValor1[qt] = new QSpinBox(groupDominio[qt]);
	spinValor1[qt]->setObjectName(QString::fromUtf8("spinValor1"));
	spinValor1[qt]->setGeometry(QRect(50, 20, 42, 22));

	comboVar[qt] = new QComboBox(groupDominio[qt]);
	comboVar[qt]->setObjectName(QString::fromUtf8("comboVar"));
	comboVar[qt]->setGeometry(QRect(90, 20, 41, 22));

	comboDominio2[qt] = new QComboBox(groupDominio[qt]);
	comboDominio2[qt]->setObjectName(QString::fromUtf8("comboDominio2"));
	comboDominio2[qt]->setGeometry(QRect(130, 20, 41, 22));

	spinValor2[qt] = new QSpinBox(groupDominio[qt]);
	spinValor2[qt]->setObjectName(QString::fromUtf8("spinValor2"));
	spinValor2[qt]->setGeometry(QRect(170, 20, 42, 22));

	tipoVar[qt] = new QComboBox(questao[qt]);
	tipoVar[qt]->setObjectName(QString::fromUtf8("tipoVar"));
	tipoVar[qt]->setGeometry(QRect(450, 40, 71, 22));

	labelTipo[qt] = new QLabel(questao[qt]);
	labelTipo[qt]->setObjectName(QString::fromUtf8("labelTipo"));
	labelTipo[qt]->setGeometry(QRect(450, 20, 46, 14));

	labelVariavel[qt] = new QLabel(questao[qt]);
	labelVariavel[qt]->setObjectName(QString::fromUtf8("labelVariavel"));
	labelVariavel[qt]->setGeometry(QRect(340, 20, 81, 20));

	labelPergunta[qt] = new QLabel(questao[qt]);
	labelPergunta[qt]->setObjectName(QString::fromUtf8("labelPergunta"));
	labelPergunta[qt]->setGeometry(QRect(10, 20, 46, 14));

	QMetaObject::connectSlotsByName(this);

// ------------------------------------------------


	questao[qt]->setWindowTitle(QApplication::translate("questao", "GroupBox", 0, QApplication::UnicodeUTF8));
	questao[qt]->setTitle(QApplication::translate("questao", tr("Quest\303\203o %1").arg(qt+1).toStdString().c_str(), 0, QApplication::UnicodeUTF8));

	labelPergunta[qt]->setText(QApplication::translate("questao", "Pergunta", 0, QApplication::UnicodeUTF8));
	linePergunta[qt]->setText(QApplication::translate("questao", "Digite sua pergunta aqui", 0, QApplication::UnicodeUTF8));

	labelVariavel[qt]->setText(QApplication::translate("questao", "Nome da Vari\303\241vel", 0, QApplication::UnicodeUTF8));
	lineVariavel[qt]->setText(QString());

	labelTipo[qt]->setText(QApplication::translate("questao", "Tipo", 0, QApplication::UnicodeUTF8));

	tipoVar[qt]->clear();
    	tipoVar[qt]->insertItems(0, QStringList()
	<< QApplication::translate("questao", "Valor Inteiro", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "Valor Real", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "Palavra", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "Booleano", 0, QApplication::UnicodeUTF8)
	);

	groupDominio[qt]->setTitle(QApplication::translate("questao", "Dom\303\255nio da vari\303\241vel", 0, QApplication::UnicodeUTF8));

	comboDominio1[qt]->clear();
	comboDominio1[qt]->insertItems(0, QStringList()
	<< QApplication::translate("questao", ">=", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "<=", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", ">", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "<", 0, QApplication::UnicodeUTF8)
	);

	comboVar[qt]->clear();
	comboVar[qt]->insertItems(0, QStringList()
	<< QString()
	<< QApplication::translate("questao", "E", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "OU", 0, QApplication::UnicodeUTF8)
	);

	comboDominio2[qt]->clear();
	comboDominio2[qt]->insertItems(0, QStringList()
	<< QString()
	<< QApplication::translate("questao", ">=", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "<=", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", ">", 0, QApplication::UnicodeUTF8)
	<< QApplication::translate("questao", "<", 0, QApplication::UnicodeUTF8)
	);

// ------------------------------------------------*/

	query *q = new query(queryList.size()+1);

	queryList.insert(queryList.size(), q);

	formLay->addWidget(q);

}
void MdiChild::adicionar(){
	novaPergunta(qt++);
//	QTableWidgetItem *a, *b, *c;

//	a = new QTableWidgetItem;
//	b = new QTableWidgetItem;
//	c = new QTableWidgetItem;

//	a->setText(campos->campos[0]->text());
//	b->setText(campos->campos[1]->text());
//	c->setText(campos->campos[2]->text());
//	tabs->setItem(quant,0,a);
//	tabs->setItem(quant,1,b);
//	tabs->setItem(quant,2,c);
//
//	quant++;
//	tabs->setRowCount(quant+1);
}

void MdiChild::remover(){

//	QList<QTableWidgetSelectionRange> ranges = tabs->selectedRanges();

//	if(ranges.size() == 1){
//		if((ranges.at(0).leftColumn() == 0)&&(ranges.at(0).rightColumn() == 2)){
//			int k = ranges.at(0).topRow();
//			for(int i = ranges.at(0).topRow(); i <= ranges.at(0).bottomRow();i++){
//				tabs->removeRow(k);
//				quant--;
//			}
//		}else tabs->setRangeSelected(ranges.at(0), false);
//	}

	int i;
	bool onceAgain = true;

	again:
	while(onceAgain){
		onceAgain = false;

		for(i=0; i< queryList.size(); i++){
				if(queryList.at(i)->checkedForRemoval()){
					delete queryList.at(i);
					queryList.removeAt(i);
					onceAgain = true;
					goto again;
				}
			}
	}

	for(i=0; i< queryList.size(); i++){
		queryList.at(i)->setNum(i+1);
	}
}

void MdiChild::monitoraSelecao(){

//	QList<QTableWidgetSelectionRange> ranges = tabs->selectedRanges();
//	if(ranges.size()>1){
//		for(int i=0; i<ranges.size();i++){
//			tabs->setRangeSelected(ranges.at(i), false);
//		}
//	}
//	else
//	if(ranges.size() == 1){
//		if((ranges.at(0).leftColumn() == 0)&&(ranges.at(0).rightColumn() == 2)){
//			//for(int i = ranges.at(0).topRow(); i <= ranges.at(0).bottomRow();i++){
//			//	removeLinha(i);
//			//}
//		}else tabs->setRangeSelected(ranges.at(0), false);
//	}
}

void MdiChild::newFile()
{
    static int sequenceNumber = 1;

    isUntitled = true;
    curFile = tr("formulario%1.talf").arg(sequenceNumber++);
    setWindowTitle(curFile + "[*]");

    //connect(document(), SIGNAL(contentsChanged()),
    //        this, SLOT(documentWasModified()));
}

bool MdiChild::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Tallulah"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(fileName)
                            .arg(file.errorString()));
        return false;
    }

    QTextStream in(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    //setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();

    setCurrentFile(fileName);

    //connect(document(), SIGNAL(contentsChanged()),
    //        this, SLOT(documentWasModified()));

   return true;
}

QString MdiChild::filename()
{
    if (isUntitled) {
        return newFilename();
    } else {
        return curFile;
    }
}

QString MdiChild::newFilename()
{
    QString filename = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                    curFile);
    /*if (fileName.isEmpty())
        return QString("");

    return saveFile(fileName);*/

    if (!filename.isEmpty()){
    	isUntitled = false;
    	curFile = filename;

    } else return QString("");

    return filename;
}

QList<query*>& MdiChild::getQueryList(){
	return queryList;
}

bool MdiChild::saveFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("MDI"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return false;
    }

    QDataStream out(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);

//	for(int i = 0; i < tabs->rowCount(); i++) {
//		for(int j = 0; j < tabs->columnCount(); j++) {
			//(tabs->itemAt(i, j)).write(&out);
//		}
//	}

    QApplication::restoreOverrideCursor();
    setCurrentFile(fileName);
    return true;
}

QString MdiChild::userFriendlyCurrentFile()
{
    return strippedName(curFile);
}

void MdiChild::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) {
        event->accept();
    } else {
        event->ignore();
    }
}

void MdiChild::documentWasModified()
{
    setWindowModified(false/*document()->isModified()*/);
}

bool MdiChild::maybeSave()
{
    if (/*document()->isModified()*/false) {
	QMessageBox::StandardButton ret;
        ret = QMessageBox::warning(this, tr("MDI"),
                     tr("'%1' has been modified.\n"
                        "Do you want to save your changes?")
                     .arg(userFriendlyCurrentFile()),
                     QMessageBox::Save | QMessageBox::Discard
		     | QMessageBox::Cancel);
        if (ret == QMessageBox::Save)
            return /*save()*/false;
        else if (ret == QMessageBox::Cancel)
            return false;
    }
    return true;
}

void MdiChild::setCurrentFile(const QString &fileName)
{
    curFile = QFileInfo(fileName).canonicalFilePath();
    isUntitled = false;
    //document()->setModified(false);
    setWindowModified(false);
    setWindowTitle(userFriendlyCurrentFile() + "[*]");
}

QString MdiChild::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}
